package com.aspire.wap.core.common;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * WTBS的本地加密（采用des算法）
 * 
 * @author huchengyi
 * @time 2009-12-17
 * @vesion 1.0.0
 * @since
 * @deprecated
 */
public class ThreeDesUtil {
	
	//threedes加密密钥
	public static final String DES_KEY = "wap&1wtbs2*threedes^5key";
	
	//threedes加密算法
	private static final String Algorithm = "DESede";
	
	/**
	 * 加密算法,可用 DES,DESede,Blowfish
	 * 
	 * @param keybyte 为加密密钥，长度为24字节
	 * @param src 为被加密的数据缓冲区（源）
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptMode(byte[] keybyte, byte[] src) throws Exception {
		// 生成密钥
		SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
		// 加密
		Cipher c1 = Cipher.getInstance(Algorithm);
		c1.init(Cipher.ENCRYPT_MODE, deskey);
		return c1.doFinal(src);
	}
	
	/**
	 * 解密算法
	 * 
	 * @param keybyte 为加密密钥，长度为24字节
	 * @param src 为加密后的缓冲区
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptMode(byte[] keybyte, byte[] src) throws Exception {
		// 生成密钥
		SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
		// 解密
		Cipher c1 = Cipher.getInstance(Algorithm);
		c1.init(Cipher.DECRYPT_MODE, deskey);
		return c1.doFinal(src);
	}

	/**
	 * 传入一个加密串，通过threedes加密输出
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception  {
//		if(args.length != 1) {
//			System.out.println("参数错误");
//			return ;
//		}
		String szSrc = "13811364536";
		
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		byte[] encoded = encryptMode(DES_KEY.getBytes(), szSrc.getBytes());
		String hexString = StringUtil.bytesToHexString(encoded);
		
		System.out.println("DES加密后 : " + hexString);
		
		System.out.println("DES解密后 : " + new String(decryptMode(DES_KEY.getBytes(),StringUtil.hexStringToBytes(hexString))));
	}
}
